package cn.itcast.web.shiro;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;




    //登录认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1. 先把token强制UsernamePasswordToken
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        //2. 得到邮箱与密码
        String email = usernamePasswordToken.getUsername();
       // String password = new String(usernamePasswordToken.getPassword()); //用户输入的密码

        //3. 根据邮箱去数据库查找一个用户
        User dbUser = userService.findByEmail(email);

        //4. 如果查找到的用户等于null，代表用户名不存在，直接返回null即可。当你返回null的时候，subject.login方法会接收到一个异常
        if(dbUser==null){
            return null;
        }

        //5. 如果用户存在，那么则通知shiro去对比密码
        /*
        SimpleAuthenticationInfo(Object principal, Object credentials, String realmName)
                principal: 登陆成功返回给controller登录成功对象
                credentials : 该用户在数据库中的密码
                realmName: 不需要管理
         */

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(dbUser,dbUser.getPassword(),"");

        return simpleAuthenticationInfo;
    }

    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1. 获取到登陆成功对象
        User loginUser = (User) principals.getPrimaryPrincipal();
        //2. 查询登陆用户拥有的权限
        List<Module> moduleList = moduleService.findModuleByUser(loginUser);

        //3.把权限添加到AuthorizationInfo对象中，这个对象拥有的权限则代表了当前用户拥有权限
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //4. 遍历用户的权限，把权限唯一标识添加到authorizationInfo对象里面
        for (Module module : moduleList) {
            authorizationInfo.addStringPermission(module.getName());//权限标记一般我们都添加
        }

        return authorizationInfo;
    }




}
